package com.example.chao.myphotosearch.api;

import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.chao.myphotosearch.PhotoSearchApp;
import com.example.chao.myphotosearch.dao.DaoMaster;
import com.example.chao.myphotosearch.dao.DaoSession;
import com.example.chao.myphotosearch.dao.Recommend;
import com.example.chao.myphotosearch.dao.RecommendContent;
import com.example.chao.myphotosearch.dao.RecommendContentDao;
import com.example.chao.myphotosearch.dao.RecommendDao;

import java.util.List;

/**
 * Created by chao on 2016/4/7.
 */
public class DbService {
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private SQLiteDatabase database;
    private static final String DATABASE_NAME = "lancer-db";
    private static DbService instance;
    public static DbService getInstance() {
        synchronized (DbService.class){
            if(instance == null){
                instance = new DbService();
            }
            return instance;
        }
    }
    private void setUpDataBase(){
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(PhotoSearchApp.getInstance(),DATABASE_NAME,null);
        database = helper.getWritableDatabase();
        daoMaster = new DaoMaster(database);
        daoSession = daoMaster.newSession();
    }

    private RecommendContentDao getRecommendContentDao(){
        if(daoSession==null)
            setUpDataBase();
        return daoSession.getRecommendContentDao();
    }
    private RecommendDao getRecommendDao(){
        if(daoSession==null)
            setUpDataBase();
        return daoSession.getRecommendDao();
    }
    public void saveRecommendList(final List<Recommend> list){
        if(list==null||list.isEmpty()){
            return;
        }
        getRecommendDao().getSession().runInTx(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < list.size(); i++) {
                    Recommend recommend = list.get(i);
                    recommend.setId((long) i);
                    getRecommendDao().insertOrReplace(recommend);
                }
            }
        });
        List<RecommendContent> recommendContents = getRecommendContentDao().queryBuilder().list();
        Log.e("RecommendContent:", recommendContents.toString());
    }

    public List<Recommend> loadAllRecommendByOrder(){
        List<Recommend> list = getRecommendDao().queryBuilder().orderAsc(RecommendDao.Properties.Id).list();
        List<RecommendContent> recommendContents = getRecommendContentDao().queryBuilder().orderAsc(RecommendContentDao.Properties.TypeId).list();
        Log.e("Recommend:",recommendContents.toString());
        return list;
    }

    public Long getTableCount(){
        return getRecommendDao().count();
    }
}
